package com.neuedu.his.service;

import com.neuedu.his.dao.*;
import com.neuedu.his.entity.*;
import com.neuedu.his.framework.BaseService;
import com.neuedu.his.framework.HisConstants;
import com.neuedu.his.framework.PageInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.List;

/**
 * 项目：      his
 * 类名:       RoleService
 * 创建时间：  2020/12/23  8:52
 * 描述 :     用户测试类
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
public class RegisterService implements BaseService<Register> {
    private RegisterDao registerDao = new RegisterDao();
    private RegisterLevelDao registerLevelDao = new RegisterLevelDao();
    private FeeItemDao feeItemDao = new FeeItemDao();
    private CheckApplyDao checkApplyDao = new CheckApplyDao();
    private InspectApplyDao inspectApplyDao = new InspectApplyDao();



    // []    {}     [{Register}]
    public List<Register> queryRegistListById(HttpServletRequest request) {


        String registerId = request.getParameter("registerId");

        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT 								");
        sql.append("   dept.name dept_name,                  ");
        sql.append("   level.name level_name,                ");
        sql.append("     user.realname ,                  ");
        sql.append("   r.*                                  ");
        sql.append(" FROM                                   ");
        sql.append("   register r                           ");
        sql.append("   LEFT JOIN USER USER           ");
        sql.append("      ON r.doctor_id = user.user_id             ");
        sql.append("   LEFT JOIN department dept            ");
        sql.append("     ON r.dept_id = dept.id             ");
        sql.append("   LEFT JOIN regist_level LEVEL         ");
        sql.append("     ON r.regsit_level_id = level.id  ");
        sql.append(" WHERE r.active = 1                     ");
        
        
        sql.append("   AND r.id=  ?               ");
      
        List<Register> list =  registerDao.selectList(sql.toString(),registerId);

        return list;
    }




    /**
     * @param request
     * @return
     */
    @Override
    public List<Register> queryList(HttpServletRequest request) {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");



        String registType = request.getParameter("registType");
        String sql = " select * from register  where active = 1   ";
        List<Register> list = null;

        if (HisConstants.REGISTER_LIST_TYPE_SELF.equals(registType)) {
            //TODO 只查今天的号 and visttime = ? 今天
            sql = "select * from register  where active = 1 and doctor_id = ? ";
            list = registerDao.selectList(sql, user.getUserId());
        }else if(HisConstants.REGISTER_LIST_TYPE_DEPT.equals(registType)) {

            //TODO   and visttime = ? 今天
            sql = "select * from register  where active = 1 and dept_id = ? and doctor_id <> ? ";
            list = registerDao.selectList(sql, user.getDeptId(),user.getUserId());
        }else{
            list = registerDao.selectList(sql);//查询所有的 病历列表  1 已挂号 2  已看诊 3 已退号
        }

        return list;
    }


    /**
     * 分页查询
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @Override
    public PageInfo queryListByPage(HttpServletRequest request) throws UnsupportedEncodingException {
        PageInfo pageInfo = getPageInfo(request);

        String name = request.getParameter("name");

        if (name == null) {
            name = "";
        }

        name = "%" + name.trim() + "%";


        //只查询 一级菜单
//        String sql = " select * from register  where  active = 1 and name like ?   ORDER BY createtime DESC  limit ?  , ?   ";

        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT 								");
        sql.append("   dept.name dept_name,                  ");
        sql.append("   level.name level_name,                ");
        sql.append("     user.realname ,                  ");
        sql.append("   r.*                                  ");
        sql.append(" FROM                                   ");
        sql.append("   register r                           ");
        sql.append("   LEFT JOIN USER USER           ");
        sql.append("      ON r.doctor_id = user.user_id             ");
        sql.append("   LEFT JOIN department dept            ");
        sql.append("     ON r.dept_id = dept.id             ");
        sql.append("   LEFT JOIN regist_level LEVEL         ");
        sql.append("     ON r.regsit_level_id = level.id  ");
        sql.append(" WHERE r.active = 1                     ");
        sql.append("   AND r.name LIKE ?               ");
        sql.append(" ORDER BY r.createtime DESC             ");
        sql.append(" LIMIT ?,?                         ");


        int start = (pageInfo.getPageNo() - 1) * pageInfo.getPageSize();
        List<Register> list = registerDao.selectList(sql.toString(), name, start, pageInfo.getPageSize());


        String sql2 = "  select count(1) from register    where active = 1 and name like ?   ";
        long count = registerDao.selectCount(sql2, name);

        pageInfo.setList(list);
        pageInfo.setTotalCount((int) count);

        return pageInfo;
    }


    @Override
    public Register queryById(Integer id) {
        return registerDao.selectById(id);
    }

    @Override
    public boolean edit(Register register) {
        return false;
    }


    /**
     * 逻辑删除，没有真正删除数据
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(Integer id) {

        return registerDao.deleteById(id);
    }

    @Override
    public boolean save(Register register) {


//        register
//        重新计算下 费用
        //
        RegisterLevel registerLevel = registerLevelDao.selectById(register.getRegsitLevelId());
        BigDecimal fee = registerLevel.getFee();//根据挂号级别查询费用
        if (register.getBook() == HisConstants.USE_BOOK) {
            fee = fee.add(new BigDecimal(1));//需要病历本 费用 +1
        }

        register.setFee(fee);

        return registerDao.insert(register);
    }

    @Override
    public boolean batchdel(String[] ids) throws Exception {
        return false;
    }

    public boolean update(Register register) {
        return registerDao.update(register);
    }


    /**
     * 退号
     * @param request
     * @return
     */
    public boolean unregist(HttpServletRequest request) {
        String id = request.getParameter("id");
        Register regsiter = registerDao.selectById(Integer.parseInt(id));

        regsiter.setStatus(HisConstants.REGISTER_STATUS_3);

        return registerDao.update(regsiter);
    }


    /**
     * 根据病历号 查询 收费项目
     * @param request
     * @return
     */
    public List<FeeItem> queryFeeItemList(HttpServletRequest request) {

        String registerId = request.getParameter("registerId");

        return feeItemDao.queryList(Integer.parseInt(registerId));
    }

    /**
     * 收费，涉及财务信息，我们简单该状态
     * @param request
     * @return
     */
    public boolean fee(HttpServletRequest request) {

        boolean success = true;


        String checckApplyIds = request.getParameter("checckApplyIds"); // 1,2,4,.....  ""
        String inspectApplyIds = request.getParameter("inspectApplyIds");//3,5,8,10,........


        String status = "2";

        String dealType = request.getParameter("dealType");
        if("refund".equals(dealType)){
            status = "4";
        }



        //更新检验的状态
        if(checckApplyIds != null && !"".equals(checckApplyIds)){
            StringBuffer sql1 =  new StringBuffer(" update check_apply set status = "+status+" where id in( ");
            String[] checkIds = checckApplyIds.split(",");
            for (String s : checkIds) {
                sql1.append("?,");
            }
            sql1.deleteCharAt(sql1.length()-1);
            sql1.append(")");

            success = success && checkApplyDao.update(sql1.toString(),checkIds);
        }

        //检验的状态修改
        if(inspectApplyIds != null && !"".equals(inspectApplyIds)){
            StringBuffer sql2 =  new StringBuffer(" update inspect_apply set status = "+status+" where id in( ");
            String[] inspectIds = inspectApplyIds.split(",");
            for (String s : inspectIds) {
                sql2.append("?,");
            }
            sql2.deleteCharAt(sql2.length()-1);
            sql2.append(")");

            success = success && inspectApplyDao.update(sql2.toString(),inspectIds);

        }

        return success;
    }
}
